package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
@SuppressWarnings("all")
public class OrderReceiver {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentFeignClient paymentFeignClient;

    /**
     * 更新订单状态，通知仓库
     * @param orderId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,autoDelete = "false"),
            key ={MqConst.ROUTING_PAYMENT_PAY}
    ))
    @SneakyThrows
    public void paySuccess(Long orderId, Message message,Channel channel){
        try {
            //判断
            if(orderId!=null){
                //查询状态
                OrderInfo orderInfo = this.orderService.getOrderInfo(orderId);
                if(orderInfo!=null && "UNPAID".equals(orderInfo.getOrderStatus())){
                    //修改状态
                    this.orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                    //发送消息，扣减库存
                    this.orderService.sendOrderStatus(orderInfo);
                }
            }
        } catch (Exception e) {
            //日志，短信通知
            e.printStackTrace();
        }
        //手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 超时订单的删除
     * 根据orderId查询订单支付状态
     * 已支付，不做处理
     * 未支付，删除订单
     *
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void orderCancel(Long orderId, Message message, Channel channel){
        try {
            //  判断订单id 是否存在！
            if (orderId!=null){
                //  根据订单Id 查询订单对象
                OrderInfo orderInfo = orderService.getById(orderId);
                //  判断
                if(orderInfo!=null && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  关闭过期订单！ 还需要关闭对应的 paymentInfo ，还有alipay.
                    //  orderService.execExpiredOrder(orderId);
                    //  查询paymentInfo 是否存在！
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    //  判断 用户点击了扫码支付
                    if(paymentInfo!=null && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                        //  查看是否有交易记录！
                        Boolean flag = paymentFeignClient.checkPayment(orderId);
                        //  判断
                        if (flag){
                            //  flag = true , 有交易记录
                            //  调用关闭接口！ 扫码未支付这样才能关闭成功！
                            Boolean result = paymentFeignClient.closePay(orderId);
                            //  判断
                            if (result){
                                //  result = true; 关闭成功！未付款！需要关闭orderInfo， paymentInfo，Alipay
                                orderService.execExpiredOrder(orderId,"2");
                            }else {
                                //  result = false; 表示付款！
                                //  说明已经付款了！ 正常付款成功都会走异步通知！
                            }
                        }else {
                            //  没有交易记录，不需要关闭支付！  需要关闭orderInfo， paymentInfo
                            orderService.execExpiredOrder(orderId,"2");
                        }
                    }else {
                        //  只关闭订单orderInfo！
                        orderService.execExpiredOrder(orderId,"1");
                    }
                }
            }
        } catch (Exception e) {
            //  写入日志...
            e.printStackTrace();
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    /**
     * 接收库存的信息，更改订单状态
     * @param strJson
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(value =@Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key =MqConst.ROUTING_WARE_ORDER ))
    public void stockOrderStatus(String strJson,Message message,Channel channel){
        try {
            if (!StringUtils.isEmpty(strJson)){
                Map<String,String>  map= JSON.parseObject(strJson, Map.class);
                String orderId = map.get("orderId");
                String status = map.get("status");
                if ("DEDUCTED".equals(status)){
                    orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);
                }else {
                    orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
                    //通过人工客服通知商家  TODO
                }
            }
        } catch (NumberFormatException e) {
            //出现异常，记录日志，或者通知程序员 TODO
            e.printStackTrace();
        }
        //手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
